﻿using System;
using System.Collections.Generic;
using FamilyBook.Core.Entities;
using FamilyBook.Core.Repositories;

namespace FamilyBook.Core.Services
{
    public class GeneralService<TEntity, TEntityId> where TEntity : class
    {
        protected readonly IGeneralRepository<TEntity, TEntityId> _repository;

        public GeneralService(IGeneralRepository<TEntity, TEntityId> repository)
        {
            if (repository == null)
                throw new ArgumentNullException("repository");

            _repository = repository;
        }

        public virtual TEntity Create(TEntity entityInstance)
        {
            var entityStatus = entityInstance as IEntityStatus;
            if (entityStatus != null && entityStatus.Status == EntityStatus.None)
                entityStatus.Status = EntityStatus.Active;

            return _repository.Create(entityInstance);
        }

        public virtual TEntity GetDetails(TEntityId entityId)
        {
            return _repository.Read(entityId);
        }

        public virtual bool TryGetDetails(TEntityId entityId, out TEntity entityInstance)
        {
            return _repository.TryRead(entityId, out entityInstance);
        }

        public virtual IEnumerable<TEntity> GetItemsList()
        {
            return _repository.ReadAll();
        }

        public virtual void Update(TEntity entityInstance)
        {
            _repository.Update(entityInstance);
        }

        public virtual void DeleteById(TEntityId entityId)
        {
            _repository.Delete(entityId);
        }

        public virtual void Delete(TEntity entityInstance)
        {
            _repository.Delete(entityInstance);
        }
    }
}
